package com.spring.zabelection.websocket;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.spring.zabelection.service.LeaderElectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.net.URI;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @program: awesome-spring
 * @description: webSocket服务器
 * @author: Alex Wu
 * @createDate: 2025-04-01 10:24
 **/

@Component
public class WebSocketServer extends TextWebSocketHandler {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private  LeaderElectionService leaderElectionService;
    private static final CopyOnWriteArrayList<WebSocketSession> sessions = new CopyOnWriteArrayList<>();


    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        String clientId = getClientIdFromUri(session.getUri());
        System.out.println("✅ New connection from Client ID: " + clientId);
        sessions.add(session);
    }

    private String getClientIdFromUri(URI uri) {
        String query = uri.getQuery();
        if (query != null && query.startsWith("clientId=")) {
            return query.substring(9);
        }
        return "Unknown";
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("📩 服务端收到信息 from " + session.getUri() + ": " + message.getPayload());

        var vote = objectMapper.readValue(message.getPayload(), Vote.class);
        leaderElectionService.receiveVote(vote.getServerId(), vote.getZxid());
    }

    public void broadcastMessage(String message) throws Exception {
        for (WebSocketSession session : sessions) {
            System.out.println("📤 服务端广发信息 to " + session.getUri() + ": " + message);
            session.sendMessage(new TextMessage(message));
        }
    }

    public static class Vote {
        private int serverId;
        private long zxid;

        private String type;

        public int getServerId() { return serverId; }
        public long getZxid() { return zxid; }

        public String getType() { return type; }
    }
}
